package bigoo.common.communication.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class SocketWrapper extends Thread {
    private Socket socket;
    private RawMessageReceiver receiver;
    private OutputStream out;
    private InputStream in;
    private boolean isRunning;
    private SocketWrapperFailuredInterested interested;

    public SocketWrapper(Socket sock, RawMessageReceiver receiver, SocketWrapperFailuredInterested interested) throws IOException {
	this.socket = sock;
	this.receiver = receiver;
	this.interested = interested;

	this.out = this.socket.getOutputStream();
	this.in = this.socket.getInputStream();
    }

    public void sendMessage(String msg) throws IOException {
	this.out.write(msg.getBytes());
	this.out.flush();
    }

    public void closeSocket() throws IOException {
	this.isRunning = false;
	this.socket.close();
    }

    public Socket getSocket() {
	return this.socket;
    }

    public void run() {
	this.isRunning = true;
	Scanner scn = new Scanner(this.in);

	try {
	    while (this.isRunning) {
		String received = scn.nextLine();
		this.receiver.processRawMessage(received, this);
	    }
	} catch (NoSuchElementException nseex) {
	    if (this.isRunning) {
		this.interested.socketClosed(this);
	    }
	}
    }
}
